package com.gobo.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gobo.eduservice.pojo.EduChapter;
import com.gobo.eduservice.mapper.EduChapterMapper;
import com.gobo.eduservice.pojo.EduVideo;
import com.gobo.eduservice.pojo.chapter.ChapterVo;
import com.gobo.eduservice.pojo.chapter.VideoVo;
import com.gobo.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gobo.eduservice.service.EduVideoService;
import com.gobo.servicebase.handler.exception.pojo.GoboException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author gobo-generator
 * @since 2021-09-19
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService eduVideoService;

    @Override
    public List<ChapterVo> getChapterVoList(String courseId) {

        //查所有的章节
        QueryWrapper<EduChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId);
        List<EduChapter> eduChapterList = baseMapper.selectList(queryWrapper);

        //查对应小节
        QueryWrapper<EduVideo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("course_id",courseId);
        List<EduVideo> eduVideoList = eduVideoService.list(queryWrapper2);
        //匹配配对
        ArrayList<ChapterVo> finnalList = new ArrayList<>();
        for (int i = 0; i < eduChapterList.size(); i++) {
            EduChapter eduChapter = eduChapterList.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            ArrayList<VideoVo> videoVos = new ArrayList<>();
            for (int j = 0; j < eduVideoList.size(); j++) {
                if (eduVideoList.get(j).getChapterId().equals(chapterVo.getId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(eduVideoList.get(j),videoVo);
                    videoVos.add(videoVo);
                }
            }
            chapterVo.setVideos(videoVos);
            finnalList.add(chapterVo);
        }
        return finnalList;
    }

    @Override
    public boolean deleteChapter(String chapterId) {
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chapter_id",chapterId);
        int count = eduVideoService.count(queryWrapper);
        if (count>0){
            throw new GoboException(30001,"章节中无小节才可删除！删除失败");
        }
        int i = baseMapper.deleteById(chapterId);
        return i>0;
    }
}
